﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Microsoft.SharePoint;

using Kiiro.SiteDefinition.Core;
using Kiiro.Common.Entities;
using Kiiro.Model;
using Kiiro.Common.Utility;
using Kiiro.SiteDefinition.ControlTemplates;
using Microsoft.SharePoint.Utilities;

namespace Kiiro.SiteDefinition.ProjectPages
{
    public partial class DocumentHistory : BasePage
    {
        public Pager V2Pager
        {
            get { return ( Pager ) v2Pager; }
        }

        public string DocumentUrl
        {
            get { return Request.QueryString [ "docUrl" ] == null ? null : Convert.ToString ( Request.QueryString [ "docUrl" ] ); }
        }

        public string Source
        {
            get { return Request.QueryString [ "Source" ] ?? ServerRelativeUrl + "/Documents.aspx"; }
        }

        protected void Page_Load ( object sender, EventArgs e )
        {
            litTitle.Text = "History";
            if ( KiiroMaster.V2Header.Project != null && !string.IsNullOrEmpty ( KiiroMaster.V2Header.Project.Title ) )
            {
                litTitle.Text = KiiroMaster.V2Header.Project.Title + " - History";
            }

            V2Pager.NextClick += new EventHandler ( RePopulatePage );
            V2Pager.PrevClick += new EventHandler ( RePopulatePage );
            V2Pager.EntitiesPerPageChange += new EventHandler ( RePopulatePage );

            PopulatePage ( );
        }

        protected void gvHistory_RowDataBound ( object sender, GridViewRowEventArgs e )
        {
            if ( e.Row.RowType == DataControlRowType.DataRow )
            {
                Document doc = ( Document ) e.Row.DataItem;

                lbDelete.Visible = !doc.IsProjectPlan;

                Literal updatedLink = ( Literal ) e.Row.FindControl ( "updatedLink" );
                updatedLink.Text = GenerateModifiedLink ( doc );

                Literal docLink = ( Literal ) e.Row.FindControl ( "docLink" );
                docLink.Text = string.Format ( "<a href=\"{0}\" onclick=\"{1}\">{2}</a>",
                    GenerateDocumentUrl ( e.Row.DataItem ),
                    GenerateOnClick ( e.Row.DataItem ),
                    FormattingHelpers.DateTimeToDisplayDateStringNoLine ( doc.ModifiedDate.ToLocalTime ( ) ) );
                Label lblSize = ( Label ) e.Row.FindControl ( "lblSize" );
                lblSize.Text = FormattingHelpers.LongBytesToDisplaySize ( doc.FileLength );

                if  ( V2Pager.PagingIndex == 0 && e.Row.RowIndex == 0 ) 
                {
                    ( ( LinkButton ) e.Row.FindControl ( "lbRevert" ) ).Visible = false;
                }
                else if ( !doc.IsProjectPlan || PermissionBitsProjectPlanFile [ 2 ] )
                {
                    ( ( LinkButton ) e.Row.FindControl ( "lbRevert" ) ).Visible = false;
                }
                else
                {
                    //this was added to solve the problem of "Revert" not showing up on the next page
                    ( ( LinkButton ) e.Row.FindControl ( "lbRevert" ) ).Visible = true;
                }
            }
        }


        protected void lbRevert_Click ( object sender, EventArgs e )
        {
            string versionLabel = ( sender as LinkButton ).CommandArgument;

            DocumentModel.RestoreVersion ( ItemId, versionLabel, CurrentUser, SiteCollectionId, ServerRelativeUrl );

            PopulatePage ( );
        }

        protected void lbDelete_Click ( object sender, EventArgs e )
        {
            Document document = new Document ( );

            document.Id = ItemId;
            document.ModifiedBy = CurrentUser;
            document.EditType = EditType.Deleted;

            DocumentModel.Save ( document, null, CurrentUser, SiteCollectionId, ServerRelativeUrl );

            Redirect ( );
        }

        private void PopulatePage ( )
        {
            if ( ItemId > 0 )
            {
                List<Document> docHistoryItems = DocumentModel.GetDocumentVersions ( ItemId, SiteCollectionId, ServerRelativeUrl );

                if ( docHistoryItems != null )
                {
                    litTitle.Text = litTitle.Text + " - " + docHistoryItems [ 0 ].Title;

                    lblFileName.Text = docHistoryItems [ 0 ].Title;
                    hlBack.NavigateUrl = Source;

                    if ( docHistoryItems.Count > 0 )
                    {
                        V2Pager.PopulatePager ( docHistoryItems.Count, Constants.PagerEntity.Documents );

                        gvHistory.DataSource = docHistoryItems.GetRange ( V2Pager.PagingIndex, V2Pager.DisplayedCount );
                        gvHistory.DataBind ( );
                    }

                    gvHistory.Rows [ gvHistory.Rows.Count - 1 ].CssClass = "borderless";
                }
                else
                {
                    Response.Redirect ( String.Format ( Constants.PortalFileUrls.SmartError, Request.Url.ToString ( ), "Document%20has%20been%20deleted%20or%20renamed." ) );
                }
            }
        }

        protected string GenerateDocumentUrl ( object dataItem )
        {
            return ( ( Document ) dataItem ).Url;
        }

        protected string GenerateOnClick ( object dataItem )
        {
            Document doc = ( Document ) dataItem;
            string extension = "";
            if ( doc.Title.Length > 0 && doc.Title.Contains ( "." ) )
                extension = doc.Title.Remove ( 0, doc.Title.LastIndexOf ( "." ) + 1 );
            if ( doc.IsFolder || CurrentUser.IsFormsUser || string.IsNullOrEmpty ( extension ) )
                return "";
            else
            {
                string absUrl = SPHelpers.GetHostHeader ( Request ) + ServerRelativeUrl;

                string docUrl = absUrl + "/" + doc.Url;
                bool canEdit = doc.IsProjectPlan ? PermissionBitsProjectPlanFile [ 2 ] : true;
                return SPHelpers.GenerateDocumentOnClick ( docUrl, extension, canEdit, absUrl );
            }
        }

        protected string GenerateModifiedLink ( Document doc )
        {
            string userDisplayUrl = ServerRelativeUrl + Constants.PortalFileUrls.UserDisplay;
            return string.Format ( "<a href='{0}?Id={1}'>{2}</a>",
                userDisplayUrl, doc.ModifiedBy.SPUserId, SPHelpers.ConvertHtmlToKiiroSafeText ( doc.ModifiedBy.FullName ) );
        }

        private void Redirect ( )
        {
            Response.Redirect ( Source );
        }

        #region Pager Related Methods

        private void RePopulatePage ( object sender, EventArgs e )
        {
            PopulatePage ( );
        }

        #endregion

    }
}

/*************************************************************************
 * 
 * $Log: /Internal Projects/Kiiro/Kiiro.SiteDefinition/12/TEMPLATE/FEATURES/Kiiro.ProjectPages/Documents/DocumentHistory.aspx.cs $
 * 
 * 32    2/08/10 5:04p Camerons
 * 
 * 31    1/25/10 1:17p Camerons
 * 
 * 30    1/20/10 3:04p Camerons
 * 
 * 29    1/18/10 3:37p Camerons
 * 
 * 28    1/12/10 12:03p Camerons
 * 
 * 27    26/11/09 10:35a Camerons
 * 
 * 26    11/26/09 10:12a Stefanf
 * 
 * 25    17/11/09 6:46p Camerons
 * 
 * 24    10/27/09 5:30p Adamw
 * accomodations for moving the plan file to the document library
 * (open/edit/version history only)
 * 
 * 23    10/26/09 9:35a Adamw
 * 
 * 22    10/23/09 5:48p Adamw
 * Case 348
 * 
 * 21    10/22/09 12:52p Adamw
 * Case 344, added CurrentUser to Model call (needed for permissions
 * check) and changed to check document CUD permissions
 * 
 * 20    10/19/09 7:01p Adamw
 * Case 349a, wrapped href = " instead of ' to allow for ' in filenames
 * and ripple of change
 * 
 * 19    30/09/09 4:08p Camerons
 * Update all links that point to UserPages, pass User.SPUserId as the
 * ItemId so that we can safely run GetOrCreateUser
 * 
 * 18    30/09/09 9:51a Shafia
 * 
 * 17    22/09/09 6:03p Camerons
 * Code changes to support creating user on demand - version 1.1.x.x
 * 
 * 16    22/09/09 9:59a Shafia
 * Implemented New Pager
 * 
 * 15    21/09/09 3:30p Camerons
 * First batch of changes for 1.1.x.x - Security groups update
 * 
 * 14    2/09/09 4:36p Camerons
 * Repair for GenerateDocOnClick
 * 
 * 13    19/08/09 12:36p Camerons
 * Modified logic in LoadGrid method to only call to get DocumentHistories
 * when Id > 0. (ie. Id = -1 when the page is being indexed) 
 * 
 * 12    17/08/09 11:07a Camerons
 * Added check-in comments section
 * 
 ************************************************************************/